<template>
    <div v-if="blogData"
        style="width: 100%;display: flex;justify-content: center;flex-direction: column;align-items: center;">
        <BlogHeader :blog="blogData" />
        <VidtorRead :content="blogData.content" />
        <BlogActionBar :blog-id="blogData.id" :is-like="blogData.isLike" :like-count="blogData.likeCount"
            :is-favorited="blogData.isFavorited" @like-blog="onLikeBlog" />
        <CommentAreaComponent :blog-id="props.id" />
    </div>
</template>

<script setup lang="ts">
import VidtorRead from '@/components/blog/VditorRead.vue';
import BlogHeader from '@/components/blog/BlogHeader.vue';
import BlogActionBar from '@/components/blog/BlogActionBar.vue';
import { BlogRead } from '@/types/blogType';
import { getValidToken, tokenAxios } from '@/utils/tokenAxiosUtils';
import { onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();

const props = defineProps({
    id: Number
})

const blogData = ref<BlogRead>();

const fetchArticle = async (id: number) => {
    console.log("获取博客数据", id)
    try {
        const res = await tokenAxios.get(`/blog/get/${id}`);
        blogData.value = res.data as BlogRead;
        console.log("获取博客数据成功", res.data)
    }
    catch (error) {
        console.error("获取博客数据失败", error)
        alert("无效的博客ID，将返回主页");
        router.push('/');
    }
}

const onLikeBlog = async () => {
    if (!getValidToken()) {
        ElMessage.error("请先登录")
        return;
    }
    try {
        if (!blogData.value.isLike) {
            const res = await tokenAxios.post(`/blogLike/add/${props.id}`);
            console.log("点赞成功：", res.data)
        }
        else {
            const res = await tokenAxios.post(`/blogLike/delete/${props.id}`);
            console.log("取消点赞成功：", res.data)
        }

        fetchArticle(props.id);
    }
    catch (error) {
        console.error("点赞/取消点赞失败：", error)
    }
}

onMounted(() => {
    fetchArticle(props.id);
})

// 监听参数变化（当在同一个组件内跳转不同ID时）
watch(() => props.id, (newId) => {
    console.log('ID变化:', props.id, newId)
    fetchArticle(newId)
})
</script>